package com.mf.controller.orderliness;

import com.mf.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: lmf
 * @Create: 2025/5/14 21:59
 * @module 有序性
 */
@RestController
@RequestMapping("orderliness")
public class Orderliness {

    private int a, b, x, y;

    @Operation(summary = "验证乱序执行效果")
    @GetMapping("validate")
    public Result<String> validate() throws InterruptedException {
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            a = 0;
            b = 0;
            x = 0;
            y = 0;

            Thread t1 = new Thread(() -> {
                a = 1;
                x = b;
            });
            Thread t2 = new Thread(() -> {
                b = 1;
                y = a;
            });
            // 按正常逻辑来说不管是t1，还是t2，先执行哪个线程，结果都是0，
            // 但是因为可能存在的乱序执行，所以有可能x=1，y=1，或者x=0，y=01
            t1.start();
            t2.start();
            t1.join();
            t2.join();

            if (x == 0 && y == 0 || x == 1 && y == 1) {
                System.out.println("第" + i + "次，x = " + x + ",y = " + y);
                return Result.success(i + "次验证出结果" + x + "--" + y);
            }
        }

        return Result.fail("验证失败");

    }

}
